package com.bittech.servlet.smallfileserver.web.config.listener;

import com.alibaba.druid.pool.DruidDataSource;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;

/**
 * Author: secondriver
 * Created: 2018/10/21
 */
@WebListener
public class DataSourceLoaderListener implements ServletContextListener {
    
    public static DataSource dataSource;
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        String url = servletContext.getInitParameter("jdbc_url");
        if (url == null || url.isEmpty()) {
            throw new IllegalArgumentException("JDBC url must be not null/empty");
        }
        String username = servletContext.getInitParameter("jdbc_username");
        if (username == null || username.isEmpty()) {
            throw new IllegalArgumentException("JDBC username  must be not null/empty");
        }
        String password = servletContext.getInitParameter("jdbc_password");
        if (password == null || password.isEmpty()) {
            throw new IllegalArgumentException("JDBC password must be not null/empty");
        }
        if (dataSource == null) {
            dataSource = new DruidDataSource();
            ((DruidDataSource) dataSource).setUrl(url);
            ((DruidDataSource) dataSource).setUsername(username);
            ((DruidDataSource) dataSource).setPassword(password);
            ((DruidDataSource) dataSource).setDriverClassName("com.mysql.jdbc.Driver");
        }
    }
    
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        dataSource = null;
    }
}
